package net.shao;

import android.app.ActivityManager;
import android.app.Application;
import android.content.pm.PackageManager;

import com.baidu.mapapi.SDKInitializer;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.socks.library.KLog;

import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by shao on 2016/7/13.
 */
public class AShaoApplication extends Application {

    private static AShaoApplication shaoApplication = new AShaoApplication();

    public static AShaoApplication getShaoApplicationInstance() {
        return shaoApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        shaoApplication = this;
        // 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
        SDKInitializer.initialize(getApplicationContext());
        //极光
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);

        // 如果APP启用了远程的service，此application:onCreate会被调用2次
        // 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
        // 默认的APP会在以包名为默认的process name下运行，
        // 如果查到的process name不是APP的process name就立即返回
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        if (processAppName == null || !processAppName.equalsIgnoreCase(shaoApplication.getPackageName())) {
            KLog.i("enter the service process!");
            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }
//        //环信
        EMOptions options = new EMOptions();
        options.setAutoLogin(true);
//        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
//        //初始化
        EMClient.getInstance().init(shaoApplication, options);
//        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(true);


    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        shaoApplication = null;
    }

}
